<template>
  <div>
    <el-form :model="params" ref="ruleForm" label-position="right" size="small" class="base-search-more" style="border: none">
      <el-form-item label="商户名称" v-if="$store.state.showAgent">
        <el-select v-model="params.agentId" filterable default-first-option placeholder="--区域--" @change="getTableList()">
          <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <div class="main">
      <pt-table-loading v-show="isloadingTable" />
      <div class="title">按规则发放的会员卡</div>
      <ul class="item">
        <li class="card" v-for="item in cardList1" :style="{ 'backgroundColor': item.baseColor}" :key="'card1'+ item.id">
          <div class="line flex-row">
            <span class="left">{{item.name}}</span><span>按规则发放</span>
          </div>
          <router-link class="path" :to="{}">查看成员</router-link>
          <div class="check flex-row">
            <span @click="addCard('0', item)">编辑</span>
            <span>{{item.isEffective == '1'? '生效中' : '已失效'}}</span>
          </div>
        </li>
        <li class="add" @click="addCard('0')">
          <i class="el-icon-plus"></i>
          <el-button class="el-text-success" type="text">新建会员卡</el-button>
        </li>
      </ul>
      <div class="title">无门槛会员卡</div>
      <ul class="item">
        <li class="card" v-for="item in cardList2"
            :style="{ 'backgroundColor': item.baseColor}" :key="'card2'+ item.id">
          <div class="line flex-row">
            <span class="left">{{item.name}}</span>
            <span>无门槛</span>
          </div>
          <router-link class="path" :to="{}">查看成员</router-link>
          <div class="check flex-row">
            <span @click="addCard('1', item)">编辑</span>
            <span>{{item.isEffective == '1'? '生效中' : '已失效'}}</span>
          </div>
        </li>
        <li class="add" @click="addCard('1')">
          <i class="el-icon-plus"></i><el-button class="el-text-success" type="text">新建会员卡</el-button>
        </li>
      </ul>
    </div>
    <el-dialog v-dialogDrag :visible.sync="dialogTableVisible" :show-close="false" width="500px" height="800">
      <template slot="title">
        <div class="back-title" @click="dialogTableVisible = false">
          <i class="el-icon-arrow-left"></i><span>返回</span>
        </div>
      </template>
      <el-form :model="from" ref="ruleForm" label-position="right" size="small" label-width="100px" class="t-body">
        <el-form-item label="背景颜色" prop="baseColor" :rules="[{ required: true, message: '会员卡颜色未选'}]">
          <el-color-picker v-model="from.baseColor" style="margin:0;padding: 0;height: 32px" />
        </el-form-item>
        <el-form-item label="会员卡名称" prop="name" :rules="[{required: true, message: '会员卡名称未填', trigger: 'blur'}]">
          <el-input style="width:300px;" v-model="from.name" />
        </el-form-item>

        <el-form-item label="会员权益" prop="memberBenefits" :rules="[{required: true, message: '折扣未填', trigger: 'blur'}]">
            <el-input-number style="width: 150px" :min='0' :max="10" :precision='1' v-model="from.memberBenefits" />
            <span style="margin-left: 10px;color:#606266;">折</span>
        </el-form-item>

        <el-form-item label="升级条件:" prop="chargeMoney" v-if="from.type == '0'" :rules="[{validator: format, trigger: 'blur' }]">
          <el-row type="flex" style="margin-bottom: 5px">
            <span class="m-title" >累计支付成功</span>
            <el-input-number style="width: 150px" :min='0' :max="9999999" :precision='0' v-model="from.tradeCounts" />
            <span style="margin-left: 10px;color:#606266;">笔</span>
          </el-row>
          <el-row type="flex" style="margin-bottom: 5px">
            <span class="m-title" >或 累计消费</span>
            <el-input-number style="width: 150px" :min='0' :max="9999999" :precision='2' v-model="from.tradeMoney" />
            <span style="margin-left: 10px;color:#606266;">{{comConfig.unit}}</span>
          </el-row>
          <el-row type="flex" style="margin-bottom: 5px">
            <span class="m-title" >或 一次性充值</span>
            <el-input-number style="width: 150px" :min='0' :max="9999999" :precision='2' v-model="from.chargeMoney" />
            <span style="margin-left: 10px;color:#606266;">{{comConfig.unit}}</span>
          </el-row>
        </el-form-item>
        <el-form-item label="会员期限:" v-if="from.type == '1'"  required>
          <el-radio v-model="from.termPype" label="0">无限期</el-radio>
          <el-radio v-model="from.termPype" label="1">有效天数</el-radio>
          <el-radio v-model="from.termPype" label="2">自定义时间</el-radio>
        </el-form-item>
        <el-form-item prop='daysCounts' v-if="from.termPype == '1'" :rules="[{required: true, message: '天数未填', trigger: 'blur' }]">
          <el-input-number style="width: 150px" :min='0' :max="100" :precision='2' v-model="from.daysCounts" />
          <span style="margin-left: 10px;color:#606266;">天</span>
        </el-form-item>
        <el-form-item v-if="from.termPype == '2'" :rules="[{required: true, message: '天数未填', trigger: 'change' }]">
          <pt-date-picker v-model="from.time" :disabledDate="time => time.getTime() <= (Date.now() - 3600 * 1000 * 24)"/>
        </el-form-item>
        <el-form-item label="过期设置:" v-if="from.type == '1'">
          <el-row type="flex">
            <span style="color:#606266;">过期后调整至</span>
            <el-select v-model="from.endChange" style="width:200px;margin:0 5px;">
              <el-option value="-1" label="非会员卡" />
              <el-option v-for="item in selectCard" :key="'select'+ item.id" :value="item.id" :label="item.name" />
            </el-select>
          </el-row>
        </el-form-item>
        <el-form-item label="同步发布至">
          <el-checkbox v-model="from.wxCardholder">微信卡包</el-checkbox>
        </el-form-item>
      </el-form>
      <div class="submit flex-row dialog-footer" slot="footer">
        <el-button v-if="from.isEffective == '0'" :loading="isdelLoading" @click="effective(true)" type="primary" plain>生效</el-button>
        <el-button style="margin-left: 5px" v-if="from.isEffective == '1'" :loading="isdelLoading" @click="effective(false)" type="warning">失效</el-button>
        <el-button style="margin-left: 5px" v-if="from.id" :loading="isdelLoading" @click="delitem()" type="danger">删除</el-button>
        <el-button style="margin-left: 5px" type="primary" :loading="issubmitLoading" @click="submitForm('ruleForm')"> 保存</el-button>
        <el-button style="margin-left: 5px" type="info" @click="dialogTableVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        params: {
          agentId: '',
          type: '',
          isEnable: ''
        },
        from: {
          id: '',
          baseColor: '',
          name: '',
          memberBenefits: undefined,
          tradeCounts: undefined,
          tradeMoney: undefined,
          chargeMoney: undefined,
          daysCounts: undefined,
          isEffective:'',
          termPype: '',
          endChange: '',
          time: '',
          type: '',
          wxCardholder: false
        },
        cardList1: [],
        cardList2: [],
        selectCard: [],
        dialogTableVisible: false,
        issubmitLoading: false,
        isdelLoading: false,
        isloadingTable: false
      }
    },
    computed: {
      restaurants() { // 区域数据
        return this.$store.state.agentList
      }
    },
    watch: {
      restaurants: {
        handler(val, oldVal) {
          if (val && val.length) {
            this.params.agentId = val[0].id
          }
        },
        deep: true
      },
      'params.agentId': {
        handler(val) {
          this.getTableList()
        },
        deep: true
      }
    },
    methods: {
      format(rule, value, callback) {
        if ((this.from.tradeCounts == '' || this.from.tradeCounts== undefined)
          && (this.from.tradeMoney == '' || this.from.tradeMoney == undefined)
          && (value == '' || value == undefined)) {
          callback(new Error('至少选一个'))
        } else {
          callback()
        }
      },
      addCard(type, item) { // 添加会员
        this.dialogTableVisible = true
         Object.assign(this.$data.from, this.$options.data().from)
        this.from.type = type
        if (item) {
          this.$nextTick(() => {
            this.from.id = item.id
            this.from.baseColor = item.baseColor || ''
            this.from.name = item.name || ''
            this.from.memberBenefits = item.memberBenefits || undefined
            this.from.tradeCounts = item.tradeCounts || undefined
            this.from.tradeMoney = item.tradeMoney || undefined
            this.from.chargeMoney = item.chargeMoney || undefined
            this.from.daysCounts = item.daysCounts || undefined
            this.from.isEffective = item.isEffective  ?item.isEffective.toString() : '0'
            this.from.termPype = item.termPype ? item.termPype.toString() : '0'
            this.from.endChange = item.endChange ? item.endChange.toString() : ''
            this.from.time = item.startDate && item.endDate ? [item.startDate, item.endDate] : ''
            this.from.wxCardholder = item.wxCardholder
          })
        }else {
        this.$nextTick(() => {
          this.$refs['ruleForm'].resetFields()
          this.from.id = ''
        });
        }
      },
      getTableList() { // 获取会员卡
        const params = { ...this.params }
        this.isloadingTable = true
        this.$http.get("/server/member/list?" + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            let arr1 = []
            let arr2 = []
            let selectList = []
            if (res.data.data.data.length > 0){
              res.data.data.data.forEach((item, index) => {
                selectList.push({id: item.id.toString(), name: item.name})
                if (item.type == '0') {
                  arr1.push(item)
                } else if (item.type == '1') {
                  arr2.push(item)
                }
              })
            }
            this.cardList1 = arr1
            this.cardList2 = ararr2r1
            this.selectCard = selectList
          }
        }).finally(() => { this.isloadingTable = false })
      },
      submitForm(formName) {  //提交数据
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const params = { ...this.from }
            params.agentId = this.params.agentId
            params.startDate = params.time ? params.time[0] : ''
            params.endDate = params.time ? params.time[1] : ''
            delete params.time
            this.issubmitLoading = true
            if (this.from.id) {
              this.$http.post('/server/member/edit', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '修改成功'})
                  this.dialogTableVisible = false
                  this.getTableList()
                }
              }).finally(() => { this.issubmitLoading = false })
            } else {
              delete params.id
              this.$http.post('/server/member/add', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '修改成功'})
                  this.dialogTableVisible = false
                  this.getTableList()
                }
              }).finally(() => { this.issubmitLoading = false })
            }
          }
        })
      },
      delitem() { // 删除
        this.isdelLoading = true
        const params ={ id: this.from.id }
        this.$http.post('/server/member/delete', JSON.stringify(params)).then((res) => {
          if(res.data.success) {
          this.$message({type: 'success', message: '删除成功'})
          this.getTableList()
          }
        }).finally(() => { this.isdelLoading = false })
      },
      effective(type) { // 生效，失效
        this.isdelLoading = true
        const params ={id: this.from.id, isEffective: type ? '1' : '0'}
        this.$http.post('/server/member/enable', JSON.stringify(params)).then((res) => {
          if(res.data.success) {
            this.$message({type: 'success', message: '删除成功'})
            this.getTableList()
          }
        }).finally(() => { this.isdelLoading = false })
      }
    },
    mounted() {
      if (this.restaurants && this.restaurants.length) {
        this.params.agentId = this.restaurants[0].id
      }
    }
  };
</script>

<style lang="scss" scoped>
  @import './css/card.scss';
</style>
